/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package acelab.tonegeneration;

import com.jsyn.engine.SynthesisEngine;
import com.jsyn.unitgen.LineOut;
import com.jsyn.unitgen.SineOscillator;
import com.jsyn.unitgen.UnitOscillator;
import java.awt.MouseInfo;

/**
 *
 * @author Administrator
 */
public class SoundOutput {

    SynthesisEngine synth;
    UnitOscillator osc;
    LineOut lineOut;
    float nextFreq = 300;
    float values[] = {300f, 600f, 1200f, 2400f};

    public SoundOutput() {
        System.out.println("Sound Engine Started!");
        synth = new SynthesisEngine();
        synth.setRealTime(true);
        // Add a tone generator.
        synth.add(osc = new SineOscillator());
        // Add an output mixer.
        synth.add(lineOut = new LineOut());
        // Connect the oscillator to the output.
        osc.output.connect(0, lineOut.input, 0);
        osc.output.connect(0, lineOut.input, 1);
    }

    public void startTone() {

        // Start synthesizer using default stereo output at 44100 Hz.
        synth.start();
        // We only need to start the LineOut. It will pull data from the oscillator.
        lineOut.start();

    }

    /*
     * Just testing.
     * This will generate a tone depending on the position of your mouse on the screen.
     * Kill this method by placing your cursor in the top left corner of the screen.
     */
    public class mouseTest implements Runnable {

        int x;
        int y;

        public void run() {
            try {
                while (true) {
                    Thread.sleep(100);
                    x = MouseInfo.getPointerInfo().getLocation().x;
                    y = MouseInfo.getPointerInfo().getLocation().y;
                    if (x == 0 && y == 0) {
                        break;
                    }
                    changeFreq(20 + x - y);
                    //System.out.println("(" + MouseInfo.getPointerInfo().getLocation().x + ", " + MouseInfo.getPointerInfo().getLocation().y + ")");
                }

            } catch (InterruptedException ex) {
            }
        }
    }

    public void changeFreq(float freq) throws InterruptedException {

        nextFreq = average(freq);
        osc.frequency.set(nextFreq);
     //   synth.sleepUntil(200.0);
     //   Synth.sleepForTicks(400);
    }

    public float average(float freq) {
        return Math.abs((freq + nextFreq) / 2.0f);
    }

    public void changeAmplitude(float amp) {
        osc.amplitude.set(amp);
    }

    public void stopTone() {
        synth.stop();
    }
}
